package com.rm.zeyou.pay.wxpay.util;

import cn.hutool.core.lang.UUID;
import com.rm.zeyou.constant.PayConstants;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.ApplicationConfigMapper;
import com.rm.zeyou.mapper.WxpayConfigMapper;
import com.rm.zeyou.pay.wxpay.constants.WechatH5LoginUrlConstants;
import com.rm.zeyou.pay.wxpay.entity.GetGlobalAccessTokenBean;
import com.rm.zeyou.pay.wxpay.entity.GetWxH5TicketBean;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.util.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 微信公众号工具类
 * @Title: WxH5Util
 * @Package com.sxskz.software.base.login.wx.officialaccounts
 * @Author ZhangKeChen  🤙🤙🏼🤙🏽
 * @Date 2023/4/28 3:54 PM
 */
@Component
@Slf4j
public class WxH5Util {

    @Resource
    private RestTemplate restTemplate;

    //@Resource
    //private WxPayEntity wxPayEntity;
    @Resource
    private ApplicationConfigMapper applicationConfigMapper;
    @Resource
    private WxpayConfigMapper wxpayConfigMapper;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取微信AccessToken
     */
    public void getWechatH5AccessToken() {
        String appAppid = applicationConfigMapper.selectOneData("app_appid");
        String accountAppid = applicationConfigMapper.selectOneData("account_appid");
        String accountSecret = applicationConfigMapper.selectOneData("account_secret");
        GetGlobalAccessTokenBean getGlobalAccessTokenBean = restTemplate.getForObject(String.format(WechatH5LoginUrlConstants.GetGlobalAccessToken,"client_credential",accountAppid,accountSecret), GetGlobalAccessTokenBean.class);
        if (! CheckEmptyUtil.isEmpty(getGlobalAccessTokenBean) && !CheckEmptyUtil.isEmpty(getGlobalAccessTokenBean.getAccessToken())) {
            log.info("获取微信公众号的access_token返回：[{}]", getGlobalAccessTokenBean);
            redisUtil.set(String.format(PayConstants.WX_H5_ACCESS_TOKEN_KEY, appAppid), getGlobalAccessTokenBean.getAccessToken());
        } else {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_H5_CONFIG_ERROR);
        }
    }

    /**
     * 获取微信Ticket
     */
    public void getWechatH5Ticket() {
        String appAppid = applicationConfigMapper.selectOneData("app_appid");
        String accountAppid = applicationConfigMapper.selectOneData("account_appid");
        String accessToken = redisUtil.get(String.format(PayConstants.WX_H5_ACCESS_TOKEN_KEY,accountAppid));
        if (CheckEmptyUtil.isEmpty(accessToken)) {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_H5_CONFIG_ERROR);
        }
        GetWxH5TicketBean getWxH5TicketBean = restTemplate.getForObject(String.format(WechatH5LoginUrlConstants.GetWxH5Ticket,accessToken,"jsapi"), GetWxH5TicketBean.class);
        if (!CheckEmptyUtil.isEmpty(getWxH5TicketBean) && !CheckEmptyUtil.isEmpty(getWxH5TicketBean.getTicket())) {
            log.info("获取微信公众号JS接口的临时票据:[{}]", getWxH5TicketBean);
            redisUtil.set(String.format(PayConstants.WX_H5_TICKET_KEY, appAppid), getWxH5TicketBean.getTicket());
        } else {
            throw new ErrorCodeException(ErrorCodeExceptionEnum.WX_H5_CONFIG_ERROR);
        }
    }

    /**
     * 获取JS-SDK签名
     *
     * @param url 当前网页的URL
     * @return
     */
    public Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8")); //对string1 字符串进行SHA-1加密处理
            signature = byteToHex(crypt.digest());  //对加密后字符串转成16进制
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }

    /**
     * 进制转换
     *
     * @param hash
     * @return
     */
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    //生成随机字符串
    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    //生成时间戳字符串
    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
